import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';

// 自定义指标
const loginErrorRate = new Rate('login_errors');
const coursesErrorRate = new Rate('courses_errors');
const registerErrorRate = new Rate('register_errors');
const loginDuration = new Trend('login_duration');
const coursesDuration = new Trend('courses_duration');
const registerDuration = new Trend('register_duration');

// 基础URL配置
const BASE_URL = 'http://localhost:8081/api';

// 测试数据
const TEST_USERS = {
  teacher: {
    account: 'teacher001',
    password: 'teacher123'
  },
  student: {
    account: 'student001', 
    password: 'student123'
  }
};

// ==================== 用户登录接口专项测试 ====================
export const loginTestOptions = {
  stages: [
    { duration: '10s', target: 5 },
    { duration: '30s', target: 15 },
    { duration: '1m', target: 25 },
    { duration: '10s', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<400'],
    http_req_failed: ['rate<0.05'],
    login_errors: ['rate<0.05'],
  },
};

export function loginTest() {
  const users = [TEST_USERS.teacher, TEST_USERS.student];
  const user = users[Math.floor(Math.random() * users.length)];
  
  const loginPayload = new URLSearchParams({
    account: user.account,
    password: user.password
  });

  const startTime = Date.now();
  const response = http.post(`${BASE_URL}/users/login`, loginPayload.toString(), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
  const endTime = Date.now();
  
  loginDuration.add(endTime - startTime);

  const success = check(response, {
    '登录状态码为200': (r) => r.status === 200,
    '登录响应时间 < 400ms': (r) => r.timings.duration < 400,
    '返回有效用户信息': (r) => {
      try {
        const body = JSON.parse(r.body);
        return body && body.userId && body.username;
      } catch (e) {
        return false;
      }
    },
    '响应包含用户角色': (r) => {
      try {
        const body = JSON.parse(r.body);
        return body && (body.role === 'teacher' || body.role === 'student');
      } catch (e) {
        return false;
      }
    },
  });

  loginErrorRate.add(!success);
  
  if (!success) {
    console.log(`登录测试失败 - 用户: ${user.account}, 状态: ${response.status}, 响应: ${response.body.substring(0, 100)}`);
  }

  sleep(0.5);
}

// ==================== 获取课程接口专项测试 ====================
export const coursesTestOptions = {
  stages: [
    { duration: '15s', target: 10 },
    { duration: '45s', target: 30 },
    { duration: '1m', target: 40 },
    { duration: '15s', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<300'],
    http_req_failed: ['rate<0.02'],
    courses_errors: ['rate<0.02'],
  },
};

export function coursesTest() {
  const startTime = Date.now();
  const response = http.get(`${BASE_URL}/courses`);
  const endTime = Date.now();
  
  coursesDuration.add(endTime - startTime);

  const success = check(response, {
    '获取课程状态码为200': (r) => r.status === 200,
    '获取课程响应时间 < 300ms': (r) => r.timings.duration < 300,
    '返回数组格式': (r) => {
      try {
        const body = JSON.parse(r.body);
        return Array.isArray(body);
      } catch (e) {
        return false;
      }
    },
    '响应内容类型正确': (r) => r.headers['Content-Type'] && r.headers['Content-Type'].includes('application/json'),
    '响应大小合理': (r) => r.body.length > 0 && r.body.length < 1000000, // 小于1MB
  });

  coursesErrorRate.add(!success);
  
  if (!success) {
    console.log(`获取课程测试失败 - 状态: ${response.status}, 响应长度: ${response.body.length}`);
  }

  sleep(0.3);
}

// ==================== 用户注册接口专项测试 ====================
export const registerTestOptions = {
  stages: [
    { duration: '20s', target: 3 },
    { duration: '40s', target: 8 },
    { duration: '1m', target: 12 },
    { duration: '20s', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<600'],
    http_req_failed: ['rate<0.1'],
    register_errors: ['rate<0.1'],
  },
};

function generateUniqueUser() {
  const timestamp = Date.now();
  const randomId = Math.floor(Math.random() * 100000);
  const vuId = __VU; // k6虚拟用户ID
  const iterationId = __ITER; // k6迭代ID
  const userAccount = `k6test${vuId}${iterationId}${timestamp}${randomId}`;
  
  return {
    userName: `K6测试用户_${vuId}_${iterationId}_${randomId}`,
    userAccount: userAccount,
    userPassword: 'k6test123456'
  };
}

export function registerTest() {
  const newUser = generateUniqueUser();
  
  const startTime = Date.now();
  const response = http.post(`${BASE_URL}/users/register`, JSON.stringify(newUser), {
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const endTime = Date.now();
  
  registerDuration.add(endTime - startTime);

  const success = check(response, {
    '注册状态码正确': (r) => r.status === 200 || r.status === 409,
    '注册响应时间 < 600ms': (r) => r.timings.duration < 600,
    '成功注册返回用户信息': (r) => {
      if (r.status === 200) {
        try {
          const body = JSON.parse(r.body);
          return body && body.userId && body.userName;
        } catch (e) {
          return false;
        }
      }
      return true; // 409状态码也算成功
    },
    '重复注册返回正确错误信息': (r) => {
      if (r.status === 409) {
        return r.body.includes('用户已存在') || r.body.includes('已存在');
      }
      return true; // 200状态码也算成功
    },
  });

  registerErrorRate.add(!success);
  
  if (!success) {
    console.log(`注册测试失败 - 用户: ${newUser.userAccount}, 状态: ${response.status}, 响应: ${response.body.substring(0, 100)}`);
  }

  sleep(1); // 注册操作间隔稍长
}

// ==================== 综合测试场景 ====================
export const options = {
  scenarios: {
    login_load_test: {
      executor: 'ramping-vus',
      exec: 'loginTest',
      startTime: '0s',
      stages: [
        { duration: '30s', target: 10 },
        { duration: '1m', target: 20 },
        { duration: '30s', target: 0 },
      ],
    },
    courses_load_test: {
      executor: 'ramping-vus', 
      exec: 'coursesTest',
      startTime: '10s',
      stages: [
        { duration: '30s', target: 15 },
        { duration: '1m', target: 25 },
        { duration: '30s', target: 0 },
      ],
    },
    register_load_test: {
      executor: 'ramping-vus',
      exec: 'registerTest', 
      startTime: '20s',
      stages: [
        { duration: '30s', target: 5 },
        { duration: '1m', target: 8 },
        { duration: '30s', target: 0 },
      ],
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<500'],
    http_req_failed: ['rate<0.05'],
    login_errors: ['rate<0.05'],
    courses_errors: ['rate<0.02'],
    register_errors: ['rate<0.1'],
  },
};

export function setup() {
  console.log('='.repeat(60));
  console.log('CourseHub 后端API压力测试开始');
  console.log('='.repeat(60));
  console.log(`测试目标: ${BASE_URL}`);
  console.log('测试场景:');
  console.log('1. 用户登录压力测试 (POST /api/users/login)');
  console.log('2. 获取课程压力测试 (GET /api/courses)');
  console.log('3. 用户注册压力测试 (POST /api/users/register)');
  console.log('测试用户: teacher001/teacher123, student001/student123');
  console.log('='.repeat(60));
  
  // 预热测试 - 验证服务是否可用
  console.log('执行预热测试...');
  
  const healthCheck = http.get(`${BASE_URL}/courses`);
  if (healthCheck.status !== 200) {
    console.error(`服务不可用! 状态码: ${healthCheck.status}`);
    throw new Error('后端服务不可用，请检查服务是否启动');
  }
  
  console.log('预热测试通过，开始正式压力测试...');
  return {};
}

export function teardown(data) {
  console.log('='.repeat(60));
  console.log('CourseHub 后端API压力测试完成!');
  console.log('='.repeat(60));
}